package com.cml.common.util;

import com.cml.application.ServerNodeApplication;
import com.cml.common.config.Configuration;
import org.apache.log4j.Logger;

import java.io.*;
import java.util.zip.Adler32;
import java.util.zip.Checksum;

/**
 * 姓名：陈茂林
 * 时间：2023/10/11 15:02
 * 描述：
 */
public class FilePersistUtils {
    private static Logger logger = Logger.getLogger(FilePersistUtils.class);
    public static Boolean persist(byte[] slotsAllocationByteArray, String slotsAllocationFilename) {
        FileOutputStream fileOutputStream =null;
        try{
            Configuration configuration = Configuration.getInstance();
            String dataDir = configuration.getDataDir();
            File file = new File(dataDir);
            if(!file.exists()){
                file.mkdir();
            }
            // 获取针对磁盘文件的一系列的输出流
            File slotAllocationFile = new File(dataDir, slotsAllocationFilename);
             fileOutputStream = new FileOutputStream(slotAllocationFile);
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
            DataOutputStream dataOutputStream = new DataOutputStream(bufferedOutputStream);
            Checksum checksum = new Adler32();
            checksum.update(slotsAllocationByteArray, 0, slotsAllocationByteArray.length);
            long checksumValue = checksum.getValue();
            dataOutputStream.writeLong(checksumValue);
            // 写入槽位分配数据的长度
            dataOutputStream.writeInt(slotsAllocationByteArray.length);
            // 写入槽位分配数据
            dataOutputStream.write(slotsAllocationByteArray);
            dataOutputStream.flush();
            //立即刷盘，防止宕机丢掉数据
            fileOutputStream.getChannel().force(true);

            return true;
        }catch (Exception e){
            logger.error("持久化槽位文件报错！！");
            logger.error(e);
            return  false;
        }finally {
            if(fileOutputStream != null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    logger.error(e);
                    return  false;
                }

            }
        }

    }
}
